package org.example.managementsystem.service;

import org.example.managementsystem.model.Schedule;
import org.example.managementsystem.repository.ScheduleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ScheduleService {

    @Autowired
    private ScheduleDao scheduleDao;

    /**
     * 自动生成指定月份的排班表
     * 按照早、中、晚三班模式，上3天班休息1天的规则
     *
     * @param year 年份
     * @param month 月份
     * @param department 部门
     * @param jobNumbers 员工工号列表
     * @return 生成的排班列表
     */
    public List<Schedule> generateMonthlySchedule(int year, int month, String department, List<String> jobNumbers) {
        if (jobNumbers == null || jobNumbers.isEmpty()) {
            throw new IllegalArgumentException("员工列表不能为空");
        }

        List<Schedule> schedules = new ArrayList<>();
        LocalDate startDate = LocalDate.of(year, month, 1);
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);

        // 定义三个班次的时间
        LocalTime morningShiftStart = LocalTime.of(8, 0);
        LocalTime afternoonShiftStart = LocalTime.of(16, 0);
        LocalTime nightShiftStart = LocalTime.of(0, 0);

        int totalDays = endDate.getDayOfMonth();
        int employeeCount = jobNumbers.size();

        // 为每个员工生成排班
        for (int empIndex = 0; empIndex < employeeCount; empIndex++) {
            String jobNumber = jobNumbers.get(empIndex);
            
            // 确定该员工的起始偏移，使不同员工的排班错开
            int offset = empIndex % 4; // 4天一个周期（3天上班，1天休息）
            
            for (int day = 1; day <= totalDays; day++) {
                // 计算当前员工在当前日期的周期位置
                int cyclePosition = (day + offset) % 4;
                
                // 如果是休息日（第4天），则跳过
                if (cyclePosition == 0) {
                    continue;
                }
                
                // 根据周期位置确定班次
                LocalTime shiftStart;
                if (cyclePosition == 1) {
                    shiftStart = morningShiftStart; // 早班
                } else if (cyclePosition == 2) {
                    shiftStart = afternoonShiftStart; // 中班
                } else {
                    shiftStart = nightShiftStart; // 晚班
                }
                
                LocalDate currentDate = LocalDate.of(year, month, day);
                LocalDateTime scheduleTime = LocalDateTime.of(currentDate, shiftStart);
                
                Schedule schedule = new Schedule();
                schedule.setJobNumber(jobNumber);
                schedule.setScheduleTime(scheduleTime);
                schedule.setDepartment(department);
                schedule.setIsActive(true);
                
                schedules.add(schedule);
            }
        }
        
        return schedules;
    }

    /**
     * 保存生成的排班表
     */
    public void saveSchedules(List<Schedule> schedules) {
        for (Schedule schedule : schedules) {
            scheduleDao.save(schedule);
        }
    }

    /**
     * 获取指定月份的排班统计信息
     */
    public Map<String, Object> getMonthlyStatistics(int year, int month, String department) {
        List<Schedule> schedules = scheduleDao.findByYearAndMonthAndDepartment(year, month, department);
        
        Map<String, Object> statistics = new HashMap<>();
        Map<String, Integer> employeeShiftCount = new HashMap<>();
        Map<String, Map<String, Integer>> shiftTypeCount = new HashMap<>();
        
        // 初始化班次类型
        String[] shiftTypes = {"早班", "中班", "晚班"};
        
        for (Schedule schedule : schedules) {
            String jobNumber = schedule.getJobNumber();
            
            // 统计每个员工的总排班数
            employeeShiftCount.put(jobNumber, employeeShiftCount.getOrDefault(jobNumber, 0) + 1);
            
            // 确定班次类型
            LocalTime time = schedule.getScheduleTime().toLocalTime();
            String shiftType;
            if (time.getHour() >= 8 && time.getHour() < 16) {
                shiftType = "早班";
            } else if (time.getHour() >= 16 || time.getHour() < 0) {
                shiftType = "中班";
            } else {
                shiftType = "晚班";
            }
            
            // 统计每个员工的班次类型数量
            if (!shiftTypeCount.containsKey(jobNumber)) {
                Map<String, Integer> typeCounts = new HashMap<>();
                for (String type : shiftTypes) {
                    typeCounts.put(type, 0);
                }
                shiftTypeCount.put(jobNumber, typeCounts);
            }
            
            Map<String, Integer> employeeTypes = shiftTypeCount.get(jobNumber);
            employeeTypes.put(shiftType, employeeTypes.get(shiftType) + 1);
        }
        
        statistics.put("totalSchedules", schedules.size());
        statistics.put("employeeShiftCount", employeeShiftCount);
        statistics.put("shiftTypeCount", shiftTypeCount);
        
        return statistics;
    }
}